/*
 * $Id: Concatenate.java,v 1.1 2014/01/23 00:12:21 jogin Exp $
 * $Name:  $
 *
 * This code is free software. It may only be copied or modified
 * if you include the following copyright notice:
 *
 * This class by Mark Thompson. Copyright (c) 2002 Mark Thompson.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * This class demonstrates copying a PDF file using iText.
 * @author Mark Thompson
 */
package us.gaaoc.framework.util.pdf;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import us.gaaoc.framework.dao.ModelFacade;
import us.gaaoc.framework.dao.ModelFacadeHibernate;
import us.gaaoc.framework.model.Documents;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PRAcroForm;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.SimpleBookmark;

/**
 * Tool that can be used to concatenate existing PDF files.
 */
public class Concatenate {

	/**
	 * This class can be used to concatenate existing PDF files. (This was an
	 * example known as PdfCopy.java)
	 * 
	 * @param args
	 *            the command line arguments
	 */
	public Concatenate(){};
	
	@SuppressWarnings("unchecked")
	public ByteArrayOutputStream Concatenating(InputStream[]fileName,  ByteArrayOutputStream outStream) {
		/*
		 * Frank if (args.length < 2) { System.err.println("arguments: file1
		 * [file2 ...] destfile"); } else {
		 */
		
		try {
			int pageOffset = 0;
			ArrayList master = new ArrayList();
			int f = 0;
			
			
			Document document = null;
			PdfCopy writer = null;
			while (f < fileName.length ) {
				// we create a reader for a certain document
				PdfReader reader = new PdfReader(fileName[f]);
				reader.consolidateNamedDestinations();
				// we retrieve the total number of pages
				int n = reader.getNumberOfPages();
				List bookmarks = SimpleBookmark.getBookmark(reader);
				
				if (bookmarks != null) {
					if (pageOffset != 0)
						SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset,
								null);
					master.addAll(bookmarks);
				}
				pageOffset += n;

				if (f == 0) {
					// step 1: creation of a document-object
					document = new Document(reader.getPageSizeWithRotation(1));
					// step 2: we create a writer that listens to the document
					writer = new PdfCopy(document,outStream);
					// step 3: we open the document
					document.open();
				}
				// step 4: we add content
				PdfImportedPage page;
				for (int i = 0; i < n;) {
					++i;
					page = writer.getImportedPage(reader, i);
					writer.addPage(page);
				}
				PRAcroForm form = reader.getAcroForm();
				if (form != null)
					writer.copyAcroForm(reader);
				f++;
			}
			if (!master.isEmpty())
				writer.setOutlines(master);
			// step 5: we close the document
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outStream;
	}
	
	public void concatenateHelper(Documents docToAppend, String packageName)
		throws IOException {
		
		byte[] docBytes = (byte[]) docToAppend.getContent();
		File  docFile =  File.createTempFile(docToAppend.getTitle(), ".pdf" , new File("C:" + File.separator + "temp" + File.separator));
		 								  
		  FileOutputStream fwd = new
		  FileOutputStream(docFile);
		  fwd.write(docBytes); 
		  fwd.flush();
		  fwd.close();
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		System.out.println("Name of the packageDoc is ......."+ packageName);
		ByteArrayOutputStream byteArrayOutputStream = 
			this.Concatenating((new FileInputStream[]
			    {new FileInputStream("C:" + File.separator + "temp" + File.separator + docFile.getName()),
					new FileInputStream(packageName)}), baos);
		
		docToAppend.setContent(null,byteArrayOutputStream.toByteArray());
		this.getModelFacade().makePersistenet(docToAppend);
		//delete the file created on the disk for security reason
		docFile.delete();
		
	}
	private ModelFacade getModelFacade() {
		return ModelFacadeHibernate.getInstance();
	}

/*
	public static void main(String args[]) {
		String fileName1 = "ChapterSection.pdf";
		String fileName2 = "SimpleAnnotations1.pdf";
		String fileName3 = "Destinations.pdf";
		
        String[] fileName = {fileName1, fileName2, fileName3};
        Concatenate concatenate = new Concatenate();
        concatenate.Concatenating(fileName);
        //Copy Destinations.pdf to ChapterSection.pdf
        concatenate.Concatenating(new String []{fileName3, fileName1});
        //fileName3 = "ChapterSection.pdf";
        
	}
*/
}

